package com.jiuye.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiuye.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author likeWen
 * @since 2022/11/1 16:37
 */
@Slf4j
//annotations指定拦截范围
//@RestControllerAdvice = @ControllerAdvice + @ResponseBody
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception ){
        // Duplicate entry 'admin' for key 'idx_username'
        log.info("exception --> {}",exception.getMessage());
        //获取异常语句
        String message = exception.getMessage();
        //重复数据的问题
        //如果message中包含Duplicate entry
        if (message.contains("Duplicate entry")){
            //以空格分割异常信息
            String[] split = message.split(" ");
            //重复的数据
            String duplicateKey = split[2];
            return R.error(duplicateKey + "===数据已经存在！");
        }
        return R.error("未知错误");
    }

    /**
     * 自定义异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        log.info(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
